/*================================================================
 *   Copyright (C) 2021 www.hsby.link All rights reserved.
 *
 *   文件名称：test_hook.cc
 *   创 建 者：汉森伯逸
 *   创建日期：2021/5/5
 *   描    述：
 *
 *================================================================*/

#include <arpa/inet.h>
#include "hsby.h"
#include "util/util.h"

void test_sleep() {
    hsby::IoManager iom(1);
    iom.AddTask([]() {
        sleep(2);
        //HSBY_LOG_SYSTEM_DEBUG << "sleep 2";
    });
    iom.AddTask([]() {
        sleep(5);
        //HSBY_LOG_SYSTEM_DEBUG << "sleep 5";
    });
    HSBY_LOG_SYSTEM_INFO << "end test_sleep()";
}

void test_socket() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    hsby::MemSetZero(addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    hsby::FdManagerSgt::Instance().Get(sock, true);
    inet_pton(AF_INET, "103.235.46.39", &addr.sin_addr.s_addr);

    HSBY_LOG_SYSTEM_INFO << "begin connect...";
    int rt = connect(sock, (const sockaddr*)&addr, sizeof(addr));
    HSBY_LOG_SYSTEM_INFO << "connect rt = " << rt << ", errno = " << strerror(errno);
    if (rt != 0) {
        return ;
    }


    HSBY_LOG_SYSTEM_INFO << "begin send...";
    auto data = "GET / HTTP/1.0\r\n\r\n";
    rt = send(sock, data, strlen(data), 0);
    HSBY_LOG_SYSTEM_INFO << "send rt = " << rt << ", errno = " << strerror(errno);
    if (rt <= 0) {
        return ;
    }

    HSBY_LOG_SYSTEM_INFO << "begin recv...";
    std::string buff;
    buff.resize(4096);
    rt = recv(sock, &buff[0], buff.size(), 0);
    HSBY_LOG_SYSTEM_INFO << "recv rt = " << rt << ", errno = " << strerror(errno);
    HSBY_LOG_SYSTEM_INFO << "recv data: \n" << buff;
    if (rt <= 0) {
        return ;
    }
}

int main() {
//    test_sleep();
    hsby::IoManager iom;
    iom.AddTask(test_socket);
    return 0;
}